const toString = Object.prototype.toString

function openPage (args) {
	let url, data = {}, dataStr = null

	switch (true) {
		case isObject(args):
			({url, data} = args)
			break
		case isString(args):
			url = args
			break
		default:
			throw new Error('参数必须是对象或者字符串')
	}

	if (isObject(data)) {
		dataStr = encodeURIComponent(JSON.stringify(data))
	} else {
		throw new Error('data数据必须是Object')
	}

	const {path, type = 'navigateTo'} = this.$minRouter[url]

	if (!['navigateTo', 'switchTab', 'reLaunch', 'redirectTo'].includes(type)) {
		throw new Error(`url:${url}里面的type必须是以下的值['navigateTo', 'switchTab', 'reLaunch', 'redirectTo']`)
	}

	return new Promise((resolve, reject) => {
		uni[type]({
			url: `/${path}?query=${dataStr}`,
			success: resolve,
			fail: reject
		})
	})
}

function parseURL () {
	const query = this.$root.$mp.query.query
	if (query) {
		return JSON.parse(decodeURIComponent(query))
	} else {
		return {}
	}
}

function isObject (value) {
	return toString.call(value) === '[object Object]'
}

function isString (value) {
	return toString.call(value) === '[object String]'
}

class MinRouter {
	constructor (urls) {
		this.urls = urls
	}
}

function install (Vue, options) {
	Vue.prototype.$minRouter = this.urls
	Vue.prototype.$openPage = openPage
	Vue.prototype.$parseURL = parseURL
}

MinRouter.prototype.install = install

export default MinRouter
